var chartCategory = null ;
var chartDataType = null ;
var chartCompletion = null ;

function refreshChart(){
    chart = new TimeChart("#chart", chartCategory);
    chart.render();
    generateCompetitorList($('#list'), competitorsByCategory[chartCategory], competitorListClicked);
    var clickCount = 4;
    $('#list input').each(function(){
        if (clickCount-- > 0) {
            this.click();
        }
    });
}

function generateCompetitorList(placeHolder, list, onclick){
    placeHolder.html("");
    $.each(list, function(){
        var div = $('<div></div>');
        var element = $('<input type=checkbox value="' + this.id + '">').click(onclick).data('competitor', this);
        div.append(element).append('<label for="' + this.id + '"><code>' + this.id + '</code> - <span style="font-size:11px">' + this.name + '</span></label>');
        if (
            ( chartCompletion == "N") ||
            ( chartCompletion == "T" && this.finished() ) || 
            ( chartCompletion == "SZ"&& this.finishedWithinTimeLimit() )
        ) {
            placeHolder.append(div);
        }
    });
}

function competitorListClicked(e){
    var target = e.target;
    var competitor = $(target).data('competitor');
    var id = competitor.id;
    if (target.checked) {
        chart.addCompetitor(id);
    }
    else {
        chart.removeCompetitor(id);
    }
    chart.render();
}


/** Time chart object which can display the distance travelled by the competitors of a category.
 * This constructor creates an empty chart, de competitrs must be added seaprately.
 */
function TimeChart(placeHolder, category){
    this.placeHolder = placeHolder;
    this.category = category;
    //this.distances = new Array();
    //for (i = 0; i < checkPoints.length; ++i) {        
    //    this.distances[i] = checkPoints[i].totalDistances[category];
    //}
    this.timeSeries = new Array();
}

/** Adds the competitor to the chart.*/
TimeChart.prototype.addCompetitor = function(id){
    var ts = [];
    for (var i = 0; i < checkPoints.length; ++i) {
        try {            
            var measurement = checkPoints[i].measurementsByCompetitor[id];
            if (chartDataType == 'relative') {
                measurement = checkPoints[i].relativeTimesByCompetitor[id];
            }
            else if (chartDataType == 'section') {
                measurement = checkPoints[i].sectionTimesByCompetitor[id];
            }            
            if (!(typeof measurement === 'undefined')) {
                //timezone hack, piece of shit: TODO:
                var time = measurement.getTime() + 7200000;
                if (chartDataType == 'relative') {
                    time = measurement.getTime() + 3600000 ;
                }
                else if (chartDataType == 'section') {
                    time = measurement.getTime() + 3600000 ;
                }
                var data = checkPoints[i].totalDistances[this.category];
                if (data >= 0) {
                    //alert(checkPoints[i].totalDistances[this.category]) ;               
                    ts.push([time, data]);
                }
            }
        } 
        catch (err) {
        }
    }
    var line = {};
    line.data = ts;
    line.label = competitorsById[id].name;
    line.id = id;
    this.timeSeries.push(line);
}

TimeChart.prototype.removeCompetitor = function(id){
    for (var i = 0; i < this.timeSeries.length; ++i) {
        if (this.timeSeries[i].id == id) {
            this.timeSeries = this.timeSeries.slice(0, i).concat(this.timeSeries.slice(i + 1));
            break;
        }
    }
}

TimeChart.prototype.render = function(){
    var checkPointTicks = new Array();
    var chart = this;
    var lastDistance = -100;
    $.each(checkPoints, function(){
        var distance = this.totalDistances[chart.category];
        if  ( distance - lastDistance > 4 ) {
            lastDistance = distance;
            checkPointTicks.push([distance, this.name + ' (' + distance + 'km)']);
        }
    });
    
    var pl = $(this.placeHolder);
    var options = {
        xaxis: {
            mode: "time"
        },
        yaxis: {
            ticks: checkPointTicks
        },
        legend: {
            position: "se"
        },
        points: {
            show: true
        },
        grid: {
            hoverable: true,
            clickable: true
        },
        selection: { mode: "xy" }
    };
    
    if (chartDataType == "section") {
        options.lines = { show: true } ;
    }
    else {
        options.lines = { show: true } ;
    }    
    
    var plot = $.plot(pl, this.timeSeries, options);

    pl.bind("plotselected", function (event, ranges) {
        /*
        alert(ranges.xaxis.from + " -> " + ranges.xaxis.to + ", " + ranges.yaxis.from + " -> " + ranges.yaxis.to) ;
        $.plot(pl, this.timeSeries,
                          $.extend(true, {}, options, {
                              xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                              yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                          }));
        */
    });

    var previousPoint = null;
    $(this.placeHolder).unbind("plothover").bind("plothover", function(event, pos, item){
        if (item) {
            if (previousPoint != item.datapoint) {
                previousPoint = item.datapoint;
                
                $("#tooltip").remove();
                y = item.datapoint[1];
                
                var d = new Date();                
                //timezone hack, piece of shit: TODO:
                if (chartDataType == 'relative') {
                    d.setTime( item.datapoint[0] - 3600000 ); 
                }
                else if (chartDataType == 'section') {
                    d.setTime( item.datapoint[0] - 3600000 );
                }
                else {
                    d.setTime( item.datapoint[0] - 7200000 ) ;
                }
                var hours = (d.getHours() < 10 ? '0' : '') + d.getHours();
                var minutes = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
                showTooltip(item.pageX, item.pageY, item.series.label + ", " + hours + ":" + minutes + ", " + y + "km");
            }
        }
        else {
            $("#tooltip").remove();
            previousPoint = null;
        }
    });
}

function showTooltip(x, y, contents){
    $('<div id="tooltip">' + contents + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}

